package com.uroad.jilinpda.util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.ImageView;


import com.uroad.lib.util.log.LogUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import sun.misc.BASE64Encoder;

/**
 * 图片相关的工具类
 */
public class ImageUtils {

    /**
     * base64字符串转化成图片
     */
    public static String GenerateImage(Context context, String imgStr) {

        //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) { //图像数据为空
            //            UtilsTools.MsgBox(context, "图片不能为空");
            return "";
        }

        try {
            //Base64解码
            //            byte[] b = Base64Utils.decode(imgStr);
            //            for (int i = 0; i < b.length; ++i) {
            //                if (b[i] < 0) {//调整异常数据
            //                    b[i] += 256;
            //                }
            //            }
            // 新生成的jpg图片
            // 新图片的文件夹, 如果没有, 就创建
            String dirPath = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/zdgj/";
            File fileDir = new File(dirPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            // 文件夹现在存在了, 可以在此文件夹下创建图片了
            String imgFilePath = dirPath + System.currentTimeMillis() + ".jpg";
            File file = new File(imgFilePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            //            out.write(b);
            out.flush();
            out.close();
            //            SharedPrefUtil.putString(context, SharedPreConstant.FacePicPathKey, imgFilePath);
            //            UtilsTools.MsgBox(context, "图片已保存到本地");
            return imgFilePath;
        } catch (Exception e) {
            //            UtilsTools.MsgBox(context, e.getMessage());
            return "";
        }
    }


    /**
     * 将图片转换成Base64编码的字符串
     *
     * @param path 图片本地路径
     * @return base64编码的字符串
     */
    public static String imageToBase64(String path) {
        String imgFile = path;//待处理的图片
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
        /*if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;*/
    }


    /**
     * 在ImageView里展示指定路径的图片
     *
     * @param path      本地路径
     * @param imageView ImageView
     */
    public static void ShowPic2View(Context context, String path, ImageView imageView) {
        try {
            Bitmap bmp = new ClipImage().getimage(path, 600, 600, 400);
            imageView.setImageBitmap(bmp);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.i("","get bitmap exception:" + e.getMessage());
        }
//        File localFile;
//        FileInputStream localStream;
//        Bitmap bitmap;
//        localFile = new File(path);
//        if (!localFile.exists()) {
//            //            UtilsTools.MsgBox(context, path + " is null.");
//        } else {
//            try {
//                localStream = new FileInputStream(localFile);
//                bitmap = BitmapFactory.decodeStream(localStream);
//                imageView.setImageBitmap(bitmap);
//                //                if (localStream != null) {
//                localStream.close();
//                //                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                //                UtilsTools.MsgBox(context, e.getMessage());
//            }
//        }
    }


    /**
     * 删除手机里指定路径的图片
     *
     * @param context Context
     * @param imgPath 本地路径
     */
    public static void DeletePicFromMobile(Context context, String imgPath) {
        try {
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = MediaStore.Images.Media.query(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=?", new String[]{imgPath}, null);
            boolean result;
            if (cursor.moveToFirst()) {
                long id = cursor.getLong(0);
                Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                Uri uri = ContentUris.withAppendedId(contentUri, id);
                int count = context.getContentResolver().delete(uri, null, null);
                result = count == 1;
            } else {
                File file = new File(imgPath);
                result = file.delete();
            }

            if (result) {
                //                UtilsTools.MsgBox(context, "删除成功");
            }
        } catch (Exception e) {
            //            UtilsTools.MsgBox(context, e.getMessage());
        }
    }
    /**
     * 解析图片并压缩转为Base64
     * @param context
     * @param path 路径
     * @return
     */
   /* public static String decodeAndCompressImg(Context context, String path, int reqWidth, int reqHeight) {
        File flie = new File(path);
        Bitmap bitmap = decodeFile(flie);
        if(reqWidth>0&&reqHeight>0){
            bitmap = decodeSampledBitmapFromByte(
                    Bitmap2Bytes(bitmap),reqWidth,reqHeight);
        }

        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
        return org.jivesoftware.smack.util.Base64.encodeBytes(ba);
    }*/


    public static Bitmap decodeFile(File f) {
        Bitmap b = null;
        int IMAGE_MAX_SIZE = 1000;
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            FileInputStream fis = new FileInputStream(f);
            BitmapFactory.decodeStream(fis, null, o);
            fis.close();

            int scale = 1;
            if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                scale = (int) Math.pow(
                        2,
                        (int) Math.round(Math.log(IMAGE_MAX_SIZE
                                / (double) Math.max(o.outHeight, o.outWidth))
                                / Math.log(0.5)));
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            fis = new FileInputStream(f);
            b = BitmapFactory.decodeStream(fis, null, o2);
            fis.close();
        } catch (IOException e) {
            return null;
        }
        return b;
    }

    public static enum ScalingLogic {
        CROP, FIT
    }

    public static Bitmap decodeSampledBitmapFromByte(byte[] res, int reqWidth,
                                                     int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(res, 0, res.length, options);

        if (reqHeight == -1) {
            options.inSampleSize = calculateSampleSize(options.outWidth,
                    options.outHeight, options.outWidth, options.outHeight,
                    ScalingLogic.CROP);
        } else {
            options.inSampleSize = calculateSampleSize(options.outWidth,
                    options.outHeight, reqWidth, reqHeight, ScalingLogic.CROP);

        }
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return getUnErrorBitmap(res, options);
    }


    private static Bitmap getUnErrorBitmap(byte[] res,
                                           BitmapFactory.Options options) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeByteArray(res, 0, res.length, options);
        } catch (OutOfMemoryError e) {
            options.inSampleSize += 1;
            return getUnErrorBitmap(res, options);
        }
        return bitmap;
    }
    public static int calculateSampleSize(int srcWidth, int srcHeight,
                                          int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float) srcWidth / (float) srcHeight;
            final float dstAspect = (float) dstWidth / (float) dstHeight;

            if (srcAspect > dstAspect) {
                return srcWidth / dstWidth;
            } else {
                return srcHeight / dstHeight;
            }
        } else {
            final float srcAspect = (float) srcWidth / (float) srcHeight;
            final float dstAspect = (float) dstWidth / (float) dstHeight;

            if (srcAspect > dstAspect) {
                return srcHeight / dstHeight;
            } else {
                return srcWidth / dstWidth;
            }
        }
    }

    /**
     * 把Bitmap转Byte
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
}